import 'package:enterprise_v6_app/app/components/custom_modele/custom_gradient_line.dart';
import 'package:enterprise_v6_app/app/components/custom_modele/custom_progress_comp_page.dart';
import 'package:enterprise_v6_app/app/components/custom_modele/custom_table.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_select_time_period.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_title_chart_page.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/data/common/charts_pie.dart';
import 'package:enterprise_v6_app/app/modules/application/double_prevention_page/risk_control_page/home/home_controller.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

class RiskManagementHomePage extends StatelessWidget {
  RiskManagementHomePage({super.key});

  final controller = Get.put(RiskManagementHomeController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: controller,
      builder: (_) {
        return Scaffold(
          backgroundColor: AppColors.bg_color_grey,
          body: ListView(
            padding: EdgeInsets.symmetric(vertical: 16.w, horizontal: 14.w),
            children: [
              _buildRiskAnalysis(),
              AppGaps.vGap10,
              _buildAssessment(),
              AppGaps.vGap10,
              _buildCancelAlarm(),
            ],
          ),
        );
      },
    );
  }

  /// 风险分析
  Widget _buildRiskAnalysis() {
    return CustomTitleChartPage(
      title: '风险分析',
      child: Column(
        children: [
          _buildRiskAnalysisInit(),
          _buildRiskAnalysisDivider(),
          _buildRiskAnalysisLeft(),
        ],
      ),
    );
  }

  /// 风险分析图例解释
  Widget _buildLegendItem(Color? color, String name, int count, {double? height, double? top}) {
    return Container(
      width: 100.w,
      height: height ?? 23.w,
      alignment: Alignment.center,
      margin: EdgeInsets.only(top: top ?? 3.w),
      child: Row(
        children: [
          Container(
            width: 10.w,
            height: 10.w,
            margin: EdgeInsets.only(right: 5.w),
            padding: EdgeInsets.all(2.w),
            decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(5.w)),
            child: Container(
              decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(5.w)),
            ),
          ),
          Text(
            name,
            style: TextStyle(fontSize: 12.w, fontWeight: FontWeight.w400, color: const Color(0xffA0A7B5)),
          ),
          const Spacer(),
          Text(
            '$count',
            style: TextStyle(
              fontSize: 12.sp,
              fontWeight: FontWeight.w400,
              color: Colors.black,
            ),
          ),
        ],
      ),
    );
  }

  /// 风险分析图表（初始）
  Widget _buildRiskAnalysisInit() {
    final annoCenter = Container(
      width: 56.w,
      height: 56.w,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(50.w),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            '初始风险',
            style: TextStyle(
              fontSize: 12.w,
              fontWeight: FontWeight.w400,
              color: const Color(0xffA0A7B5),
            ),
          ),
          Text(
            '${controller.initRiskCount}',
            style: TextStyle(fontSize: 16.w, fontWeight: FontWeight.w400, color: const Color(0xFF495061)),
          ),
        ],
      ),
    );
    return SizedBox(
      height: 120.w,
      child: SfCircularChart(
        legend: Legend(
          isVisible: true,
          height: 170.w.toString(),
          position: LegendPosition.right,
          overflowMode: LegendItemOverflowMode.none,
          legendItemBuilder: (String name, dynamic series, dynamic point, int seriesIndex) {
            final item = controller.initRiskData[seriesIndex];
            final child = _buildLegendItem(
              item.color,
              name,
              item.y.toInt(),
              height: 19.w,
              top: 3.w,
            );
            if (seriesIndex == 0) {
              return Padding(
                padding: EdgeInsets.only(top: 13.w),
                child: child,
              );
            }
            return child;
          },
          toggleSeriesVisibility: false,
        ),
        annotations: [
          CircularChartAnnotation(
            widget: controller.leftRiskCount == 0
                ? Stack(
                    alignment: Alignment.center,
                    children: [
                      annoCenter,
                      SizedBox(
                        width: 73.w,
                        height: 73.w,
                        child: CircularProgressIndicator(
                          strokeWidth: 7.w,
                          value: 1,
                          valueColor: const AlwaysStoppedAnimation<Color>(Color(0xFFFC9900)),
                        ),
                      ),
                    ],
                  )
                : annoCenter,
          ),
        ],
        series: <CircularSeries>[
          DoughnutSeries<ChartData, String>(
            dataSource: controller.initRiskData,
            pointColorMapper: (ChartData data, _) => data.color,
            xValueMapper: (ChartData data, _) => data.x,
            yValueMapper: (ChartData data, _) => data.y,
            name: '初始风险',
            dataLabelSettings: const DataLabelSettings(
              isVisible: false,
              labelPosition: ChartDataLabelPosition.inside,
            ),
            radius: '100%',
            innerRadius: '75%',
            enableTooltip: true,
          ),
        ],
      ),
    );
  }

  /// 风险分析图表（分割线）
  Widget _buildRiskAnalysisDivider() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        _buildTextInDivider(
          '管控措施${controller.analysis?.riskMeasuresCount ?? 0}条',
          Alignment.center,
        ),
        _buildTextInDivider(
          '应急预案${controller.analysis?.emergencyPlanCount ?? 0}条',
          Alignment.center,
        ),
        _buildTextInDivider(
          '安全培训${controller.analysis?.safetyTrainingCount ?? 0}条',
          Alignment.center,
        ),
      ],
    );
  }

  Widget _buildTextInDivider(String text, Alignment align) {
    return Align(
      alignment: align,
      child: Text(
        text,
        style: TextStyle(color: Colors.blue, fontSize: 12.w),
      ),
    );
  }

  /// 风险分析图表（剩余）
  Widget _buildRiskAnalysisLeft() {
    final annoCenter = Container(
      width: 56.w,
      height: 56.w,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(50.w),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            '剩余风险',
            style: TextStyle(
              fontSize: 12.w,
              fontWeight: FontWeight.w400,
              color: const Color(0xffA0A7B5),
            ),
          ),
          Text(
            '${controller.leftRiskCount}',
            style: TextStyle(fontSize: 16.w, fontWeight: FontWeight.w400, color: const Color(0xFF495061)),
          ),
        ],
      ),
    );
    return SizedBox(
      height: 120.w,
      child: SfCircularChart(
        legend: Legend(
          height: 130.w.toString(),
          isVisible: true,
          position: LegendPosition.right,
          alignment: ChartAlignment.center,
          overflowMode: LegendItemOverflowMode.none,
          legendItemBuilder: (String name, dynamic series, dynamic point, int seriesIndex) {
            final item = controller.leftRiskData[seriesIndex];
            final child = _buildLegendItem(
              item.color,
              name,
              item.y.toInt(),
              height: 19.w,
              top: 3.w,
            );
            if (seriesIndex == 0) {
              return Padding(
                padding: EdgeInsets.only(top: 13.w),
                child: child,
              );
            }
            return child;
          },
          toggleSeriesVisibility: false,
        ),
        annotations: [
          CircularChartAnnotation(
            widget: controller.leftRiskCount == 0
                ? Stack(
                    alignment: Alignment.center,
                    children: [
                      annoCenter,
                      SizedBox(
                        width: 73.w,
                        height: 73.w,
                        child: CircularProgressIndicator(
                          strokeWidth: 7.w,
                          value: 1,
                          valueColor: const AlwaysStoppedAnimation<Color>(Color(0xFFFC9900)),
                        ),
                      ),
                    ],
                  )
                : annoCenter,
          ),
        ],
        series: <CircularSeries>[
          DoughnutSeries<ChartData, String>(
            dataSource: controller.leftRiskData,
            pointColorMapper: (ChartData data, _) => data.color,
            xValueMapper: (ChartData data, _) => data.x,
            yValueMapper: (ChartData data, _) => data.y,
            name: '剩余风险',
            dataLabelSettings: const DataLabelSettings(
              isVisible: false,
              labelPosition: ChartDataLabelPosition.inside,
            ),
            radius: '100%',
            innerRadius: '75%',
            enableTooltip: true,
          ),
        ],
      ),
    );
  }

  /// 机制运行效果及评估
  Widget _buildAssessment() {
    if (controller.assessment == null) {
      return const SizedBox();
    }
    return CustomTitleChartPage(
      title: '机制运行效果及评估',
      titleRightWidget: Stack(
        alignment: Alignment.center,
        children: [
          SizedBox(
            width: 28.w,
            height: 18.w,
            child: SvgPicture.asset(AppImages.icon_red_trapezoid),
          ),
          Text(
            controller.assessmentLevel ?? '未知',
            style: TextStyle(color: Colors.white, fontSize: 10.w),
          )
        ],
      ),
      child: Column(
        children: [
          CustomProgressComp(
            width: 263.w,
            height: 6.w,
            bgColor: const Color(0xFFEFF7FF),
            topTitle: _buildProgressTitle(
              '风险分析',
              controller.assessment?.analysisCount ?? 0,
              controller.assessment?.analysisRate ?? 0,
            ),
            linearGradient: const LinearGradient(
              begin: Alignment.centerRight,
              end: Alignment.centerLeft,
              colors: [Color(0xFF9DCFFF), Color(0xFF33A9FF)],
            ),
            value: (controller.assessment?.analysisRate ?? 0) / 100,
            isShowTitle: false,
            isShowIcon: false,
          ),
          CustomProgressComp(
            width: 263.w,
            height: 6.w,
            bgColor: const Color(0xFFEFF7FF),
            topTitle: _buildProgressTitle(
              '排查任务',
              controller.assessment?.investigationCount ?? 0,
              controller.assessment?.investigationRate ?? 0,
            ),
            linearGradient: const LinearGradient(
              begin: Alignment.centerRight,
              end: Alignment.centerLeft,
              colors: [Color(0xFF9DCFFF), Color(0xFF33A9FF)],
            ),
            value: (controller.assessment?.investigationRate ?? 0) / 100,
            isShowTitle: false,
            isShowIcon: true,
          ),
          CustomProgressComp(
            width: 263.w,
            height: 6.w,
            bgColor: const Color(0xFFEFF7FF),
            topTitle: _buildProgressTitle(
              '隐患整改',
              controller.assessment?.rectificationCount ?? 0,
              controller.assessment?.rectificationRate ?? 0,
            ),
            linearGradient: const LinearGradient(
              begin: Alignment.centerRight,
              end: Alignment.centerLeft,
              colors: [Color(0xFF9DCFFF), Color(0xFF33A9FF)],
            ),
            value: (controller.assessment?.rectificationRate ?? 0) / 100,
            isShowTitle: false,
            isShowIcon: true,
          ),
        ],
      ),
    );
  }

  /// 机制运行效果及评估 进度条 标题
  Widget _buildProgressTitle(String title, double count, double rate) {
    return Row(
      children: [
        SizedBox(
          width: 100.w,
          child: Text(
            title,
            style: TextStyle(
              fontSize: 12.sp,
              fontWeight: FontWeight.w400,
              color: const Color(0xff333333).withOpacity(0.5),
            ),
          ),
        ),
        Icon(Icons.arrow_left_outlined, size: 20.sp, color: const Color(0xffFD6B6B)),
        Text(
          '总数：$count',
          style: TextStyle(
            fontSize: 12.sp,
            fontWeight: FontWeight.w400,
            color: const Color(0xff495061),
          ),
        ),
        const Spacer(),
        Text(
          '$rate%',
          style: TextStyle(
            fontSize: 12.sp,
            fontWeight: FontWeight.w500,
            color: const Color(0xff417EFB),
          ),
        ),
      ],
    );
  }

  /// 报警
  Widget _buildCancelAlarm() {
    return CustomTitleChartPage(
      title: '报警',
      child: Column(
        children: [
          CustomSelectTimePeriod(
            onConfirm: (_, __) {},
          ),
          AppGaps.vGap10,
          _buildCancelAlarmSummary(),
          AppGaps.vGap10,
          SizedBox(
            height: 120.w,
            child: SfPyramidChart(
              legend: Legend(
                isVisible: true,
                height: 133.w.toString(),
                position: LegendPosition.right,
                alignment: ChartAlignment.center,
                overflowMode: LegendItemOverflowMode.scroll,
                legendItemBuilder: (String name, dynamic series, dynamic point, int seriesIndex) {
                  final item = controller.alarmData[seriesIndex];
                  final child = _buildLegendItem(item.color, name, 0, height: 20.w);
                  if (seriesIndex == 0) {
                    return Padding(
                      padding: EdgeInsets.only(top: 13.w),
                      child: child,
                    );
                  }
                  return child;
                },
                toggleSeriesVisibility: false,
              ),
              series: PyramidSeries<ChartData, String>(
                gapRatio: 0.1,
                dataSource: controller.alarmData,
                xValueMapper: (ChartData data, _) => data.x,
                yValueMapper: (ChartData data, _) => data.y,
                textFieldMapper: (datum, index) => '${datum.x}：${datum.y}',
                pointColorMapper: (datum, index) => datum.color,
                width: 80.w.toString(),
                height: 80.w.toString(),
              ),
            ),
          ),
          _buildChartExplain(),
          AppGaps.vGap10,
          _buildHistory(),
        ],
      ),
    );
  }

  /// 消警 概要
  Widget _buildCancelAlarmSummary() {
    return Container(
      decoration: BoxDecoration(color: const Color(0x1A5C6DFF), borderRadius: BorderRadius.all(Radius.circular(8.w))),
      child: Padding(
        padding: EdgeInsets.all(10.w),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            _buildCancelAlarmSummaryTop('未处理'),
            CustomVerticalGradientLine(height: 24.w),
            _buildCancelAlarmSummaryTop('消警'),
            CustomVerticalGradientLine(height: 24.w),
            _buildCancelAlarmSummaryTop('超时'),
            CustomVerticalGradientLine(height: 24.w),
            _buildCancelAlarmSummaryTop('误报'),
          ],
        ),
      ),
    );
  }

  /// 消警 概要 顶部
  Widget _buildCancelAlarmSummaryTop(String type) {
    const color = Color.fromARGB(255, 102, 116, 245);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '0',
          style: TextStyle(
            color: color,
            fontWeight: FontWeight.w500,
          ),
        ),
        AppGaps.vGap10,
        Text(
          type,
          style: const TextStyle(
            color: color,
            fontWeight: FontWeight.w500,
          ),
        ),
      ],
    );
  }

  /// 消警 图表 解释
  Widget _buildChartExplain() {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFFF7F7FD),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: controller.alarmData
            .map((e) => _buildChartExplainItem(
                  e.x,
                  e.color ?? Colors.brown,
                ))
            .toList(),
      ),
    );
  }

  /// 消警 图表 解释 单个
  Widget _buildChartExplainItem(String title, Color c) {
    return ListTile(
      title: Row(
        children: [
          Container(
            height: 8.w,
            width: 24.w,
            decoration: BoxDecoration(
              color: c,
              borderRadius: BorderRadius.circular(5.w),
            ),
          ),
          AppGaps.hGap10,
          Text(
            title,
            style: TextStyle(color: const Color(0xFF495061), fontWeight: FontWeight.w500, fontSize: 12.w),
          ),
        ],
      ),
      subtitle: Text(
        '未处理0条，消警0条，超时0条，误报0条',
        style: TextStyle(
          color: const Color(0xFF8393AC),
          fontSize: 12.w,
        ),
      ),
    );
  }

  /// 消警 底部 历史表格
  Widget _buildHistory() {
    return CustomTable(
      xLen: 4,
      yLen: 3,
      alignment: Alignment.center,
      cellPadding: EdgeInsets.all(6.w),
      cellBuilder: (x, y) {
        return Text(
          '$x * $y',
          style: TextStyle(
            color: const Color(0xFF818499),
            fontSize: 12.w,
          ),
        );
      },
      headBuilder: (x) => Text(
        controller.tableTitle[x],
        style: TextStyle(
          fontWeight: FontWeight.w500,
          fontSize: 12.w,
        ),
      ),
    );
  }
}
